// Copyright (c) 2021 Presto Labs Pte. Ltd.
// Author: gekim

#pragma once

#include <string>

#include <rapidjson/document.h>
#include <rapidjson/rapidjson.h>

#include "coin/proto/coin_market_enums.pb.h"
#include "coin2/base/conversion.h"
#include "coin2/exchange/base/feed/update.h"
#include "coin2/exchange/base/feed_util/book_builder.h"
#include "coin2/exchange/base/feed_util/trade.h"

namespace impl {
using coin2::exchange::base::market::ExchangeType;
using coin2::exchange::base::market::MarketType;

class KucoinFeedUpdateParser {
 public:
  static bool ParseBook(BookBuilder* book_builder_,
                        const rapidjson::Value& book_json) {
    if (book_json.HasMember("asks") && book_json.HasMember("bids") &&
        book_json.HasMember("timestamp")) {
      auto ts =
          std::llround(stod(book_json["timestamp"].GetString()) * 1'000'000LL);
      auto tx = book_builder_->NewTransaction(ts);
      tx.Clear();
      for (const auto& pq : book_json["bids"].GetArray()) {
        tx.UpdateBid(stod(pq[0].GetString()), stod(pq[1].GetString()));
      }
      for (const auto& pq : book_json["asks"].GetArray()) {
        tx.UpdateAsk(stod(pq[0].GetString()), stod(pq[1].GetString()));
      }
      return true;
    }

    return false;
  }
  static bool ParseBookL2(BookBuilder* book_builder_,
                          const rapidjson::Value& book_json,
                          bool is_light_bbo) {
    int64_t ts= 0;
    if (book_json.HasMember("time")) {
      ts = std::llround(stod(book_json["time"].GetString()) * 1'000'000LL);
    }
    auto tx = book_builder_->NewTransaction(ts);
    if (is_light_bbo) {
      tx.BboClear();
    }

    if (book_json["changes"].HasMember("bids")) {
      for (const auto& pq : book_json["changes"]["bids"].GetArray()) {
        tx.UpdateBid(stod(pq[0].GetString()), stod(pq[1].GetString()));
      }
    }
    if (book_json["changes"].HasMember("asks")) {
      for (const auto& pq : book_json["changes"]["asks"].GetArray()) {
        tx.UpdateAsk(stod(pq[0].GetString()), stod(pq[1].GetString()));
      }
    }
    return true;
  }
  static void ParseTrade(const rapidjson::Value& trade_json, Trade* trade, int64_t timestamp) {
    trade->price = stod(trade_json["price"].GetString());
    trade->fill_qty = stod(trade_json["size"].GetString());
    trade->side = ParseTradeSide(trade_json["side"].GetString());
    trade->timestamp = timestamp;
  }

  static coin2::exchange::feed::TradeSide ParseTradeSide(const std::string& side) {
    if (side == "buy") {
      return coin2::exchange::feed::TRADE_BUY_SIDE;
    } else if (side == "sell") {
      return coin2::exchange::feed::TRADE_SELL_SIDE;
    } else {
      throw std::runtime_error("[Kucoin] unknown side: " + side);
    }
  }

  static fastfeed::proto::KlineInterval ParseKlineInterval(std::string_view interval) {
    static std::map<std::string, fastfeed::proto::KlineInterval> interval_map = {
      {"1min", fastfeed::proto::KLINE_INTERVAL_1MIN},
      {"3min", fastfeed::proto::KLINE_INTERVAL_3MIN},
      {"5min", fastfeed::proto::KLINE_INTERVAL_5MIN},
      {"15min", fastfeed::proto::KLINE_INTERVAL_15MIN},
      {"30min", fastfeed::proto::KLINE_INTERVAL_30MIN},
      {"1hour", fastfeed::proto::KLINE_INTERVAL_1HOUR},
      {"1day", fastfeed::proto::KLINE_INTERVAL_1DAY}
    };

    auto iter = interval_map.find(std::string(interval));
    if (iter == interval_map.end()) {
      return fastfeed::proto::KLINE_INTERVAL_INVALID;
    }

    return iter->second;
  }

  static bool ParseKlineRest(
      const rapidjson::Value& msg,
      Klines* klines,
      fastfeed::proto::KlineInterval interval,
      int64_t timestamp) {
    const auto& v = msg.GetArray();
    CHECK_EQ(v.Size(), 7);
    int64_t open_timestamp = stod(v[0].GetString()) * 1'000'000'000LL;
    auto result = klines->AddKline(open_timestamp);
    if (!result) return false;

    Kline* kline;
    bool freezed;
    std::tie(kline, freezed) = result.value();
    kline->open_timestamp = open_timestamp;
    kline->open = stod(v[1].GetString());
    kline->close = stod(v[2].GetString());
    kline->high = stod(v[3].GetString());
    kline->low = stod(v[4].GetString());
    kline->volume = stod(v[5].GetString());
    kline->turnover = stod(v[6].GetString());
    kline->timestamp = timestamp;
    kline->interval = interval;

    return freezed;
  }
};
}  // namespace impl

using impl::KucoinFeedUpdateParser;
